/**
 * author:  chenxc
 * date:    2022/11/19
 */
import {
  Client,
  type frameCallbackType,
  StompSubscription,
} from '@stomp/stompjs';
import { MQ_SERVICE_DEV, MQ_SERVICE_PROD, MQ_USERNAME, MQ_PASSWORD} from "@/constant/websocket";
const envMode = import.meta.env.MODE;
const mq_service = envMode.indexOf("dev") > -1 ? MQ_SERVICE_DEV : MQ_SERVICE_PROD;

export interface subConfigType {
  destination: string;
  callback: frameCallbackType;
}
export class WebSocketClient {
  client: Client;
  subInstance: StompSubscription[] = [];
  constructor(url: string = mq_service, username: string = MQ_USERNAME, password: string = MQ_PASSWORD) {
    if(username && password){
      this.client = new Client({
        brokerURL: url,
        connectHeaders: {
          login: username,
          passcode: password,
        },
        debug: (str: string) => {
           // console.log(str);
        },
        reconnectDelay: 5000,
        heartbeatIncoming: 4000,
        heartbeatOutgoing: 4000,
      });
    }
    else{
      console.log('未提供用户名和密码');
      this.client = new Client({
        brokerURL: url,
      });

    }

  }
  connect(subConfig?: subConfigType[]) {
    this.client.onConnect = (frame) => {
      console.log(`${new Date().toLocaleString()} ws-Connected: ` + frame);
      this.#sub(subConfig);
    };
    return this;
  }
  disconnect() {
    this.client.deactivate().then(() => {
      console.log(`${new Date().toLocaleString()} ws-断开连接成功`);
    });
    return this;
  }
  onStompError(callback?: frameCallbackType) {
    if (callback) {
      this.client.onStompError = callback;
    } else {
      this.client.onStompError = function (frame) {
        console.log('Broker reported error: ' + frame.headers['message']);
        console.log('Additional details: ' + frame.body);
      };
    }
    return this;
  }
  run() {
    this.client.activate();
    return this;
  }
  pub(destination: string, body: string, callback?: Function) {
    if (this.client.connected) {
      // 发布消息
      // 在发送之前调用回调函数
      callback && callback();
      this.client.publish({
        destination: destination,
        body: body,
        headers: undefined,
      });
      console.log(`${new Date().toLocaleString()} ws-发布消息成功:`, body);
    }
    return this;
  }
  // 私有方法，读取定义的订阅配置
  #sub(subConfig?: subConfigType[]) {
    subConfig?.forEach((config) => {
      this.subInstance.push(
        this.client.subscribe(config.destination, config.callback),
      );
      console.log(
        `${new Date().toLocaleString()} ws-订阅成功:`,
        config.destination,
      );
    });
    return this;
  }
}
